/*@ 自定义命名空间，便于识别，维护，管理 @*/
/* 定义全局顶层命名空间（模拟） */
/* # 缩写单词解释
ckArgs -- callback args
*/
/* 全局函数原型式内容扩展 */
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function(m, i) {
            return args[i];
        });
}

var abtsec = {};

/*@ 模态框相关 @*/
abtsec.modal = abtsec.hasOwnProperty("modal") || {};
/* 模态框selector定义 */
$(function() {
    abtsec.modal.object = {
        loading: $("#abte-modal-loading"),
        prompt: $("#abte-modal-prompt"),
        common: $("#abte-modal-common")
    };
});
/* 模态框显示/隐藏事件通用定义 */
abtsec.modal.comm = function(typeStr, status, statusEvent, callback, ckArgs) {
    /* 先清空之前的事件 */
    abtsec.modal.object[typeStr].off('hidden.bs.modal');
    abtsec.modal.object[typeStr].off('shown.bs.modal');
    /* 先隐藏掉加载模态框 */
    abtsec.modal.object[typeStr].modal(status);
    /* 当所有隐藏效果完成时，再调用真实的回调函数 */
    if (callback && typeof(callback) != 'undefined') {
        abtsec.modal.object[typeStr].on(statusEvent,
            function() { callback.apply(null, ckArgs); });
    }
}
/* 模态框隐藏事件定义 */
abtsec.modal.hide = function(typeStr, callback, ckArgs) {
    abtsec.modal.comm(typeStr, 'hide', 'hidden.bs.modal', callback, ckArgs);
}
/* 模态框显示事件定义 */
abtsec.modal.show = function(typeStr, callback, ckArgs) {
    abtsec.modal.comm(typeStr, 'show', 'shown.bs.modal', callback, ckArgs);
}
/* 通用操作模态框定义 */
abtsec.modal.common = function(content, status, ckArgs) {
    abtsec.modal.object.common.find(".modal-title").empty().html(ckArgs.title);
    abtsec.modal.object.common.find(".modal-body").empty().html(content);
    abtsec.modal.show("common");
}
/* 操作确认模态框定义 */
abtsec.modal._prompt = function(tipContent, cfmCallback, ckArgs) {
    var cttObj = abtsec.modal.object.prompt.find(".modal-body");
    var cfmBtn = abtsec.modal.object.prompt.find(".abts-btn-click");
    cttObj.empty().html(tipContent);
    cfmBtn.unbind('click');
    cfmBtn.bind("click", function() {
        /* 点击之后，关闭模态框再回调 */
        abtsec.modal.hide("prompt", cfmCallback, ckArgs);
    });
    /* 显示模态框 */
    abtsec.modal.show("prompt");
}
/* 操作提示模态框定义 */
abtsec.modal.prompt = function(flag, tipContent, nxtCallback, ckArgs) {
    if (flag == 'ok') {
        var sflag = '<span class="glyphicon glyphicon-ok abts-ico-result abts-ico-result-ok"></span>';
    } else if (flag == 'rm') {
        var sflag = '<span class="glyphicon glyphicon-remove abts-ico-result abts-ico-result-error"></span>';
    } else {
        var sflag = '<span class="glyphicon glyphicon-info-sign abts-ico-result text-yellow"></span>';
    }
    /* 输出显示 */
    abtsec.modal._prompt(sflag + tipContent, nxtCallback, ckArgs);
}
/* 操作结果提示模态框定义 */
abtsec.modal.result = function(isSucs, tipContent, nxtCallback, ckArgs) {
    if (isSucs == 0) {
        var sflag = '<span class="glyphicon glyphicon-ok abts-ico-result abts-ico-result-ok"></span>';
    } else {
        var sflag = '<span class="glyphicon glyphicon-remove abts-ico-result abts-ico-result-error"></span>';
    }
    /* 输出显示 */
    abtsec.modal._prompt(sflag + tipContent, nxtCallback, ckArgs);
}

/*@ ajax相关 @*/
abtsec.ajax = abtsec.hasOwnProperty("ajax") || {};
/* 封装 ajax 的回调函数 */
abtsec.ajax.callback = function(callback, ckArgs) {
    return function(resp, status, xhr) {
        abtsec.modal.hide("loading", callback, [resp, status, ckArgs]);
    }
}
/* ajax 通用的 异步加载内容 */
abtsec.ajax.common = function(method, url, data, callback, ckArgs) {
    abtsec.modal.show("loading", method, [url, data, abtsec.ajax.callback(callback, ckArgs)]);
}
/* ajax load 异步回调函数 */
abtsec.ajax.load_callback = function(url, data, callback, ckArgs) {
    $(ckArgs.selector).empty();
    $(ckArgs.selector).load(url, data, abtsec.ajax.callback(callback, ckArgs));
}
/* ajax load 异步加载内容 */
abtsec.ajax.load = function(url, data, callback, ckArgs) {
    abtsec.modal.show("loading", abtsec.ajax.load_callback, [url, data, callback, ckArgs]);
}
/* ajax get 异步加载内容 */
abtsec.ajax.get = function(url, data, callback, ckArgs) {
    abtsec.ajax.common($.get, url, data, callback, ckArgs);
}
/* ajax post 异步加载内容 */
abtsec.ajax.post = function(url, data, callback, ckArgs) {
    abtsec.ajax.common($.post, url, data, callback, ckArgs);
}
/* ajax 先关闭父级模态框，再打开回显新内容 */
abtsec.ajax.replace = function(url, data, callback, ckArgs) {
    /* 先关闭父级modal，再打开新modal */
    var modalType = "common";
    if (ckArgs.mtype && typeof(ckArgs.mtype) != 'undefined') {
        modalType = ckArgs.mtype;
    }
    var ajaxMeth = abtsec.ajax.get;
    if (ckArgs.ajaxmeth && typeof(ckArgs.ajaxmeth) != 'undefined') {
        ajaxMeth = ckArgs.ajaxmeth;
    }
    abtsec.modal.hide(modalType, ajaxMeth, [url, data, callback, ckArgs]);
}

/*@ 动态选项卡相关 @*/
abtsec.tab = abtsec.hasOwnProperty("tab") || {};
/* 定义tab的缓存内容 */
abtsec.tab.cache = {}
/* 定义tab的初始化方法 */
abtsec.tab.init = function(selector) {
    abtsec.tab.cache[selector] = $(selector).tabs();
    /* 创建标签项的关闭事件委托 */
    abtsec.tab.cache[selector].delegate("span.ui-icon-close", "click", function() {
        var rmele = $(this).closest("li");
        var mapid = rmele.attr("aria-controls");
        /* 移除tab标签li和tab内容div */
        rmele.remove();
        $("#" + mapid).remove();
        /* 刷新 tab 显示 */
        abtsec.tab.cache[selector].tabs("refresh");
    });
}
/* 定义tab的焦点事件 */
abtsec.tab.focus = function(selector, tabid) {
    /* 获取待激活的tab标签页索引 */
    var idx = abtsec.tab.cache[selector].children('.ui-tabs-nav').
    children('li[aria-controls="' + tabid + '"]').index();
    /* 若存在则直接切换，不存在则动态加载 */
    if (idx >= 0) {
        abtsec.tab.cache[selector].tabs("option", "active", idx);
        return true;
    } else { return false; }
}
/* 定义tab的添加事件 */
abtsec.tab.append = function(selector, url, title, tabid) {
    /* 去掉id里面的非法字符去掉 */
    tabid = tabid.replace(/\//g, '').toUpperCase();
    /* 判断是否已存在，若存在则切换，不存在，则动态加载 */
    if (abtsec.tab.focus(selector, tabid) !== true) {
        var tabitem = '<li aria-controls="' + tabid + '"><a href="#' + tabid + '">' + title +
            '</a><span class="ui-icon ui-icon-close" style="float:right;" ' +
            'role="presentation">Remove Tab</span></li>';
        /* 异步加载内容 */
        var ckArgs = { "selector": selector, "tabitem": tabitem, "tabid": tabid }
        abtsec.ajax.get(url, null, abtsec.tab.append_callback, ckArgs);
    }
}
/* 添加tab append事件的回调函数 */
abtsec.tab.append_callback = function(resp, status, ckargs) {
    abtsec.tab.cache[ckargs.selector].children(".ui-tabs-nav").append(ckargs.tabitem);
    abtsec.tab.cache[ckargs.selector].append('<div id="' + ckargs.tabid + '">' + resp + '</div>');
    abtsec.tab.cache[ckargs.selector].tabs("refresh");
    abtsec.tab.focus(ckargs.selector, ckargs.tabid);
}
/* 定义tab的添加事件 */
abtsec.tab.append_maintab = function(title, data, refresh) {
    var args = data.split(':');
    var tabid = "DYNTABSID" + args[1];
    var url = args[0] + "?sid=" + args[1];
    var cssel = '#abte-tabs-main';

    /* 判断是否需要先关闭已存在的 */
    if (refresh === true) {
        var selector = 'li[aria-controls="' + tabid.toUpperCase() + '"] span.ui-icon-close';
        abtsec.tab.cache[cssel].find(selector).click();
    }
    /* 动态添加tab页面内容 */
    abtsec.tab.append(cssel, url, title, tabid);
}

/*@ form表单操作相关 @*/
abtsec.form = abtsec.hasOwnProperty("form") || {};
/* 表单提交事件绑定 */
abtsec.form.bind = function(formSeletor, sucsFunc, beforeFunc, errorFunc, ckArgs) {
    $(formSeletor).ajaxForm({
        dataType: 'json',
        beforeSend: function(xhr) {
            abtsec.modal.show("loading");
            if (beforeFunc && (typeof(beforeFunc) != 'undefined')) {
                return beforeFunc(xhr, ckArgs);
            }
        },
        success: function(resp, status, xhr) {
            abtsec.modal.hide("loading", sucsFunc, [resp, status, ckArgs]);
        },
        error: function(xhr, status) {
            abtsec.modal.hide("loading", errorFunc, [xhr, status, ckArgs]);
        }
    });
}
/* 表单操作的通用回调函数 */
abtsec.form.comm_callback = function(resp, status, ckArgs) {
    abtsec.modal.result(resp.sucs, resp.msg);
}

/* form表单全局 xsrf */
abtsec.form.xsrf = function() {
    return $("#abte-xsrf-global").attr("data");
}

/*@ 重定向相关函数定义 @*/
abtsec.redirect = abtsec.hasOwnProperty("redirect") || {};
/* 自身页面重定向 */
abtsec.redirect.self = function(redirectUrl) {
    if (redirectUrl) { location.href = redirectUrl; }
}

/*@ 提示信息相关函数定义 @*/
abtsec.tip = abtsec.hasOwnProperty("tip") || {};
/* 提示信息函数 */
abtsec.tip.info = function(resp, status, ckArgs) {
    if (resp.sucs == 0) {
        var content = '<span class="glyphicon glyphicon-ok margin-right-8"></span>';
        $(ckArgs.selector).removeClass("text-red").addClass("text-green").empty().html(content + resp.msg);
    } else {
        var content = '<span class="glyphicon glyphicon-remove margin-right-8"></span>';
        $(ckArgs.selector).removeClass("text-green").addClass("text-red").empty().html(content + resp.msg);
    }
}
abtsec.tip.alert = function(resp, status, ckArgs) {
    abtsec.modal.result(resp.sucs, resp.msg);
}
abtsec.tip.obj_info = function(resp, status, ckArgs) {
    if (resp.sucs == 0) {
        var content = '<span class="glyphicon glyphicon-ok margin-right-8"></span>';
        ckArgs.obj.removeClass("text-red").addClass("text-green").empty().html(content + resp.msg);
    } else {
        var content = '<span class="glyphicon glyphicon-remove margin-right-8"></span>';
        ckArgs.obj.removeClass("text-green").addClass("text-red").empty().html(content + resp.msg);
    }
}
/* 添加列表项，并输出提示信息函数 */
abtsec.tip.add_item_info = function(resp, status, ckArgs) {
    if (resp.sucs == 0) {
        var content = '<span class="glyphicon glyphicon-ok margin-right-8"></span>';
        $(ckArgs.tipSelector).removeClass("text-red").addClass("text-green").empty().html(content + resp.msg);
        /* 给指定的列表添加子项 - 判断是调用哪个处理函数 */
        if (ckArgs.itemSelector && typeof(ckArgs.itemSelector) != 'undefined') {
            $(ckArgs.itemSelector).append(abtsec.content.replace(ckArgs.tplHtml, resp.items));
        } else {
            ckArgs.callback(resp);
        }
    } else {
        var content = '<span class="glyphicon glyphicon-remove margin-right-8"></span>';
        $(ckArgs.tipSelector).removeClass("text-green").addClass("text-red").empty().html(content + resp.msg);
    }
}
/* 追加列表项，并输出提示信息函数 */
abtsec.tip.append_item_info = function(resp, status, ckArgs) {
    if (resp.sucs == 0) {
        /* 给指定的列表添加子项 */
        $(ckArgs.itemSelector).append(resp.msg);
    } else {
        abtsec.modal.result(resp.sucs, resp.msg);
    }
}

/*@ 内容操作相关函数定义 @*/
abtsec.content = abtsec.hasOwnProperty("content") || {};
/* 内容模板参数替换值 */
abtsec.content.replace = function(tplHtml, jsonObj) {
    $.each(jsonObj, function(key, val) {
        var pattern = new RegExp("<!--\\s*" + key + "\\s*-->", "gmi");
        tplHtml = tplHtml.replace(pattern, val);
    });
    return tplHtml;
}

/*@ dom元素操作相关函数定义 @*/
abtsec.dom = abtsec.hasOwnProperty("dom") || {};
/* dom元素内容模板参数替换 */
abtsec.dom.html_repalce = function(html, datas, selector) {
    if (datas.length > 0) {
        var allItems = '';
        for (var item in datas) {
            allItems += abtsec.content.replace(html, item);
        }
        $(selector).empty().html(allItems);
    }
}

/*@ 认证相关函数定义 @*/
abtsec.auth = abtsec.hasOwnProperty("auth") || {};
/* 认证回调处理函数 - 模态框提示信息模式 */
abtsec.auth.modal_callback = function(resp, status, ckArgs) {
    /* 判断是否需要输出提示信息 */
    if (resp.msg) {
        abtsec.modal.result(resp.sucs, resp.msg, abtsec.redirect.self, [resp.redirect]);
    } else {
        abtsec.redirect.self(resp.redirect);
    }
}

/*@ 图片相关函数定义 @*/
abtsec.image = abtsec.hasOwnProperty("image") || {};
/* 验证码更新事件绑定 */
abtsec.image.captcha = function(imgSelector) {
    $(imgSelector).on("click", function() {
        $(this).attr("src", $(this).attr("src").split("?")[0] + '?' + new Date().getTime());
    });
}

/*@ 按钮相关函数定义 @*/
abtsec.button = abtsec.hasOwnProperty("button") || {};
/*@ 按钮赋值函数定义 */
abtsec.button.submit_set_val = function(e) {
    /* 先清空并列的 submit 的值 */
    $(e.data.formSelector).find("button[type=submit]").val("");
    /* 再设置当前按钮对象的值 */
    $(this).val($(this).attr("name"));
    /* 返回 true，继续form提交 */
    return true;
}

/*@ 高度相关函数定义 @*/
abtsec.height = abtsec.hasOwnProperty("height") || {};
/* 不同div的高度统一起来 */
abtsec.height.same_max = function(selectors) {
    /* 先查找最高的div的 height 值 */
    var maxHeight = 0,
        curHeight = 0;
    for (var sect in selectors) {
        curHeight = $(sect).height();
        // console.log(">>>>"+curHeight);
        if (curHeight > maxHeight) {
            maxHeight = curHeight;
        }
    }
    /* 依次遍历所有的div，设置最大高度 */
    selectors.forEach(function(sect) {
        $(sect).height(maxHeight);
    });
}

/*@ 定位相关函数定义 @*/
abtsec.position = abtsec.hasOwnProperty("position") || {};
/* 永远在文档底部(注不是屏幕底部) */
abtsec.position.bottom = function(selector) {
    var posObject = $(selector);
    var objHeight = posObject.outerHeight(true);
    var marginTop = ($(window).scrollTop() + $(window).height() - objHeight) + "px";
    //如果页面内容高度小于屏幕高度，div#footer将绝对定位到屏幕底部，否则div#footer保留它的正常静态定位 
    if (($(document.body).height() + objHeight) < $(window).height()) {
        posObject.css({
            position: "absolute",
            top: marginTop
        });
    } else {
        posObject.css({
            position: "static"
        });
    }
    // 窗口大小变化事件监听 - 启用后，卡顿厉害
    // abtsec.position.change(selector);
}
abtsec.position.change = function(selector) {
    $(window).scroll(function() { abtsec.position.bottom(selector); })
        .resize(function() { abtsec.position.bottom(selector); });
}

/*@ 图表相关函数定义 @*/
abtsec.echarts = abtsec.hasOwnProperty("echarts") || {};
/* 不同div的高度统一起来 */
abtsec.echarts.data_refresh = function(resp, status, ckArgs) {
    ckArgs.option.series[0].data = [resp.data];
    ckArgs.echart.init(document.getElementById(ckArgs.selector)).setOption(ckArgs.option);
    // 执行自定义(定制化)的函数
    if (ckArgs.callback && (typeof(ckArgs.callback) != 'undefined')) {
        ckArgs.callback(resp.extra);
    }
}

/*@ 综合操作相关函数定义 @*/
abtsec.multi = abtsec.hasOwnProperty("multi") || {};
/* 操作结果对象替换提示信息 */
abtsec.multi.ajax_td_result = function(args) {
    var vals = args.obj.attr("data").split('?');
    abtsec.ajax.post(vals[0], vals[1], abtsec.tip.obj_info, {
        obj: args.obj.closest("td")
    });
}
/* 操作结果弹框提示信息 */
abtsec.multi.ajax_alert_result = function(args) {
    var vals = args.obj.attr("data").split('?');
    abtsec.ajax.post(vals[0], vals[1], abtsec.tip.alert, args.ckargs);
}
/* 加载更多操作 */
abtsec.multi.ajax_more = function(callback, args) {
    /* args.btn */
    var vals = args.btn.attr("data").split('?');
    abtsec.ajax.post(vals[0], vals[1] + args.btn.attr("title"), function(resp, status, ckargs) {
        /* 判断是否获取到内容 */
        if (resp.sucs == 0 && resp.items.length > 0) {
            callback(resp);
            ckargs.btn.attr("title", parseInt(ckargs.btn.attr("title")) + 1);
        } else {
            ckargs.btn.empty().html("已加载全部！").attr("disabled", true);
        }
    }, args);
}

/*@ 事件绑定相关函数定义 @*/
abtsec.bind = abtsec.hasOwnProperty("bind") || {};
/* 动态添加tab页事件绑定 */
abtsec.bind.ajax_tab = function(menuSelector, tabSelector) {
    $(menuSelector).click(function() {
        /* 样式切换 */
        $(menuSelector).removeClass("abts-menu-active");
        $(this).addClass("abts-menu-active");
        /* 获取基础数据 */
        var url = $(this).attr('data');
        var tabid = "DYNTABSID" + url;
        /* 获取tab标签页的标题 */
        var title = $(this).attr('title');
        title = title ? title : $(this).text();
        /* 执行 */
        abtsec.tab.append(tabSelector, url, title, tabid);
    });
}
/* Post模式获取视图按钮事件绑定 - 比如使用post来获取view视图页面的 */
abtsec.bind.ajax_view = function(selector, pselector) {
    // 交换位置 a = [b,b=a][0];
    if (pselector && typeof(pselector) != 'undefined') {
        selector = [pselector, pselector=selector][0];
    }

    $(selector).on("click", pselector, function() {
        var urls = $(this).attr("data").split('?');
        abtsec.ajax.post(urls[0], urls[1], abtsec.modal.common, {
            title: $(this).text()
        });
    });
}
/* 基础数据下发更新 */
abtsec.bind.ajax_dist = function(selector, pselector) {
    // 交换位置
    if (pselector && typeof(pselector) != 'undefined') {
        selector = [pselector, pselector=selector][0];
    }
    
    $(selector).on('click', pselector, function() {
        abtsec.modal.prompt($(this).attr("title"), "基础数据【下发更新】到后台处理器中，是否继续操作？",
            abtsec.multi.ajax_alert_result, [{ obj: $(this) }]);
    });
}
/* 基础数据审核 */
abtsec.bind.ajax_audit = function(selector, pselector) {
    // 交换位置
    if (pselector && typeof(pselector) != 'undefined') {
        selector = [pselector, pselector=selector][0];
    }
    $(selector).on('click', pselector, function() {
        abtsec.modal.prompt($(this).attr("title"), "审核【" + $(this).text() + "】，是否继续操作？",
            abtsec.multi.ajax_td_result, [{ obj: $(this) }]);
    });
}

/*@ 表格相关操作 @*/
abtsec.table = abtsec.hasOwnProperty("table") || {};
/* 表格添加序号 */
abtsec.table.add_index = function(selector, eidx) {
    var sidx = 1;
    var trsum = $(selector + ' tr').length;
    var firstd = $(selector + ' tr:eq(1) td:first');
    /* 判断从第几个开始 */
    if (eidx > 0) { sidx = eidx; }

    if (typeof(firstd.attr("colspan")) == "undefined") {
        for (var i = sidx; i < trsum; i++) {
            $(selector + ' tr:eq(' + i + ') td:first').text(i);
        }
    }
}
/* 表格行tr内容刷新 */
abtsec.table.row_refresh = function(args) {
    // 发送post请求，获取响应内容，并调用回调函数处理
    var vals = args.obj.attr("data").split('?');
    var ridx = args.obj.parent().parent().index();
    abtsec.ajax.post(vals[0], vals[1] + "&rowidx=" + ridx, args.callback);
}

/*@ 所有自定义的函数定义 - 每个service自定义的函数 @*/
abtsec.private = abtsec.hasOwnProperty("private") || {};